package com.threader.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

import org.apache.log4j.Logger;


public class Config {
	private static final Logger logger = Logger.getLogger(Config.class);

	static {
		init();
	}
	private static void init() {
		String defaultPropertiesPath = System.getProperty("config.default.filepath");
		if (defaultPropertiesPath == null)
			defaultPropertiesPath = "defaultProperties";

		// create and load default properties
        Properties defaultProps = new Properties();
		try {
			logger.info("Reading default config file : " + defaultPropertiesPath);
			FileInputStream in = new FileInputStream(defaultPropertiesPath);
			defaultProps.load(in);
			in.close();
		} catch (FileNotFoundException fe) {
			System.out.println("Error reading default properties file, system can not start properly!!!");
		} catch (IOException ioe) {
			System.out.println("Error reading default properties file, system can not start properly!!!");
		}
		// create program properties with default
		applicationProps = new Properties(defaultProps);

		// if override path is specified, read the override configs.
		String configPath = System.getProperty("config.filepath");
		if (configPath != null && configPath.trim().length() != 0) {
			try {
				FileInputStream cin = new FileInputStream(configPath);
				logger.info("Reading custom config properties file : "
						+ configPath);
				applicationProps.load(cin);
				cin.close();
			} catch (FileNotFoundException fe) {
				System.out.println("Error reading custom config properties file : "
						+ configPath + "\nUsing default configuration!!!");
			} catch (IOException ioe) {
				System.out.println("Error reading default properties file, system can not start properly!!!");
			}
		}
	}	

	private static Properties applicationProps;
	
	public static String getProperty(String key) {
		String retval = applicationProps.getProperty(key);
		return retval==null?null:retval.trim();
	}

	public static String getProperty(String key, String defaultValue) {
		String retval = Config.getProperty(key);
		if (StringUtils.isEmpty(retval))
			return defaultValue;
		return retval;
	}

	public static boolean getPropertyAsBoolean(String key) {
		String retval = Config.getProperty(key);
        return "TRUE".equalsIgnoreCase(retval) || "1".equalsIgnoreCase(retval);
    }

	public static void setProperty(String name, String value) {
		applicationProps.setProperty(name, value);
	}

	public static boolean isProperty(String key) {
		String retval = Config.getProperty(key);
        return !StringUtils.isEmpty(retval) && Boolean.parseBoolean(retval);
    }
}
